package com.bjsxt.service.impl;

import com.bjsxt.mapper.MenuMapper;
import com.bjsxt.pojo.Menu;
import com.bjsxt.pojo.PageA;
import com.bjsxt.pojo.TreeA;
import com.bjsxt.service.MenuService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class MenuServiceimpl implements MenuService {
    @Autowired
    private MenuMapper menuMapper;

    //查询指定角色下的菜单
    @Override
    public List<TreeA> findMore(Integer aid, Integer pid) {
        List<Menu> list = menuMapper.selectMore(aid, pid);
        List<TreeA> li = new ArrayList<>();
        for (Menu menu : list) {
            TreeA t = new TreeA(menu.getMid(), menu.getMname(), menu.getStatus() == 0 ? "closed" : "open", menu.getUrl());
            li.add(t);
        }
        return li;
    }

    //查询所有菜单的实现
    @Override
    public PageA<Menu> findAll(Integer page, Integer rows) {

        Page pg = PageHelper.startPage(page, rows);

        List<Menu> list = menuMapper.selectAll();

        PageA<Menu> pga = new PageA<>(list, pg.getTotal());

        return pga;
    }
//异步树下查询指定角色所有菜单
    @Override
    public List<TreeA> findAll2(Integer pid) {
        List<Menu> list = menuMapper.selectAll2(pid);

        List<TreeA> li = new ArrayList<>();
        for (Menu menu : list) {
            TreeA t = new TreeA(menu.getMid(), menu.getMname(), menu.getStatus() == 0 ? "closed" : "open", menu.getUrl());
            li.add(t);
        }
        return li;
    }
//添加菜单实现
    @Override
    public Integer insertMenu(Menu menu) {
        return menuMapper.insert(menu);
    }
//修改菜单的实现
    @Override
    public Integer change(Menu menu) {
        return menuMapper.update(menu);
    }
//删除菜单操作
    @Override
    public Integer delete(Integer mid) {
        List<Menu> list = menuMapper.selectAll2(mid);
        if (list.size()>0){
            return -1;
        }
        return menuMapper.delete(mid);
    }
    //查询同步树形菜单的实现
    @Override
    public List<TreeA> findAll3() {
        //一级菜单集合
        List<TreeA> list1 = menuMapper.selectAll3(0);
        for (TreeA t:list1){
            //TreeA--- 一级菜单
            //相当于二级菜单
            Integer id = t.getId();
            //当前一级 TreeA下对应的二级菜单list2
            List<TreeA> list2 = menuMapper.selectAll3(id);
            //把二级菜单保存到一级菜单中
            t.setChildren(list2);


        }
        return list1;
    }


}
